package exercise.基础练习;

import java.util.HashMap;

/**
 * 给你两个字符串 s1 和 s2 ，写一个函数来判断 s2 是否包含 s1 的排列。如果是，返回 true ；否则，返回 false 。
 *
 * 换句话说，s1 的排列之一是 s2 的 子串 。
 * 示例 1：
 *
 * 输入：s1 = "ab" s2 = "eidbaooo"
 * 输出：true
 * 解释：s2 包含 s1 的排列之一 ("ba").
 * 示例 2：
 *
 * 输入：s1= "ab" s2 = "eidboaoo"
 * 输出：false
 *  
 *
 * 提示：
 *
 * 1 <= s1.length, s2.length <= 104
 * s1 和 s2 仅包含小写字母
 */
public class LC567_字符串的排列 {
    public static void main(String[] args) {
        System.out.println(checkInclusion("iab","eidbaiooo"));
    }

    public static boolean checkInclusion(String s1, String s2) {
        HashMap<Character,Integer> needMap = new HashMap<>();
        HashMap<Character,Integer> windowMap = new HashMap<>();
        for(int i = 0;i < s1.length();i++){
            needMap.put(s1.charAt(i),needMap.getOrDefault(s1.charAt(i),0) + 1);
        }
        int left = 0,right = 0,valid = 0;
        int res_length = Integer.MAX_VALUE;
        while(right < s2.length()){
            char c_in = s2.charAt(right++);
            if(needMap.get(c_in) != null){
                windowMap.put(c_in,windowMap.getOrDefault(c_in,0) + 1);
                if(windowMap.get(c_in).equals(needMap.get(c_in))){
                    valid++;
                }
            }
            //写法1：满足需求后再移动左窗口
/*            while(valid == needMap.size()){
                if(right - left < res_length){
                    res_length = right - left;
                    if(res_length == s1.length()){
                        return true;
                    }
                }
                char c_out = s2.charAt(left++);
                if(needMap.get(c_out) != null){
                    if(windowMap.get(c_out).equals(needMap.get(c_out))){
                        valid--;
                    }
                    windowMap.put(c_out,windowMap.get(c_out) - 1);
                }
            }*/
            //写法2：窗口大小达到s1的长度就移动左窗口
            while(right - left >= s1.length()){
                if (valid == needMap.size()){
                    return true;
                }
                char c_out = s2.charAt(left++);
                if (needMap.get(c_out) != null){
                    if (windowMap.get(c_out).equals(needMap.get(c_out))){
                        valid--;
                    }
                    windowMap.put(c_out,windowMap.get(c_out) - 1);
                }
            }
        }
        return false;
    }
}
